package uk.co.davedexter.flickruploader;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.xml.parsers.ParserConfigurationException;

import org.xml.sax.SAXException;

import com.aetrion.flickr.Flickr;
import com.aetrion.flickr.FlickrException;
import com.aetrion.flickr.REST;
import com.aetrion.flickr.RequestContext;
import com.aetrion.flickr.auth.Auth;
import com.aetrion.flickr.auth.AuthInterface;
import com.aetrion.flickr.auth.Permission;
import com.aetrion.flickr.people.User;
import com.aetrion.flickr.photos.Photo;
import com.aetrion.flickr.photos.PhotoList;
import com.aetrion.flickr.photos.PhotosInterface;
import com.aetrion.flickr.photos.SearchParameters;
import com.aetrion.flickr.tags.Tag;
import com.aetrion.flickr.util.FileAuthStore;

public class SearchTest2 {
	
	private Flickr flickr;
	private FileAuthStore store;
	AuthInterface authInterface;
	Auth auth;
	
	private static String apiKey = "1a703d7aaa61bb936903ef46ab76cf02";
	private static String secret = "60946c09ae777c88";
	
	SearchTest2() {
		try {
			flickr = new Flickr(apiKey, secret, new REST());
			authInterface = flickr.getAuthInterface();
			
			RequestContext rc = RequestContext.getRequestContext();
			
			File authDir = new File("src/authstore2");
			if (authDir.exists() & authDir.isDirectory()) {
				System.out.println("Loading existing authorisation.");
				store = new FileAuthStore(authDir);
				auth = store.retrieve("47213205@N04");
				rc.setAuth(auth);
			} else {
				// Prompt the user.
				String frob = authInterface.getFrob();
				URL url = authInterface.buildAuthenticationUrl(Permission.READ,
						frob);
				System.out
						.println("Press return after you granted access at this URL:");
				System.out.println(url.toExternalForm());
				BufferedReader infile = new BufferedReader(new InputStreamReader(
						System.in));
				infile.readLine();
				auth = authInterface.getToken(frob);
				
				rc.setAuth(auth);
				
				store = new FileAuthStore(new File("src/authstore2"));
	            store.store(auth);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (FlickrException e) {
			e.printStackTrace();
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		}
	}
	
	private void search(String text, String[] tags) {
		try {
			
			System.out.println("Token: " + auth.getToken());
            System.out.println("nsid: " + auth.getUser().getId());
            System.out.println("Realname: " + auth.getUser().getRealName());
            System.out.println("Username: " + auth.getUser().getUsername());
            System.out.println("Permission: " + auth.getPermission());
			
			PhotosInterface photoInt = flickr.getPhotosInterface();
			SearchParameters searchParams = new SearchParameters();
	        searchParams.setMedia("photos");
	        String tagsText = "";
	        for (String t : tags) { 
	        	tagsText += "" + t.toLowerCase().replaceAll("[ .,:;'@-_=+)(*&^%$£!`]", "") + " ";
	        	System.out.println(t.toLowerCase().replaceAll("[ .,:;'@-_=+)(*&^%$£!`]", ""));
        	}
	        
	        searchParams.setText("" + text + " " + tagsText);
	        searchParams.setUserId("47213205@N04");
	        System.out.println(auth.getToken());
//	        searchParams.setTagMode("All");
//	        searchParams.setTags(tags);
	        
	        PhotoList results = photoInt.search(searchParams, 50, 0);
			System.out.println(results.size());
			Iterator<Photo> itr = results.iterator();
			while (itr.hasNext()) {
			       Photo p = itr.next();
			       User user = flickr.getPeopleInterface().getInfo(p.getOwner().getId());
			       System.out.println(p.getTitle());
			       Photo photowithtags = photoInt.getInfo(p.getId(), p.getSecret());
			       Collection t = photowithtags.getTags();
			       for (Object tag : t) {
			    	   System.out.println(((Tag) tag).getRaw());
			       }
			}
		} catch (FlickrException fe) {
			fe.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		SearchTest2 test = new SearchTest2();
		String[] searchTags = {"Ann's bits"};
//		String[] searchTags = {"hongkongsep08"};
		test.search("Ann's bits 060.jpg", searchTags);
	}

}
